package com.androidbegin.jsonparsetutorial;

import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.androidbegin.jsonparsetutorial.*;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;

public class MainActivity extends Activity {
	// Declare Variables
	JSONObject jsonobject;
	JSONArray jsonarray;
	ListView listview;
	ListViewAdapter adapter;
	EditText inputSearch;
	ProgressDialog mProgressDialog;
	ArrayList<HashMap<String, String>> arraylist;
	static String ID = "id";
	static String CONTENT = "content_detail";
	static String IMAGE = "image_thumbnail";
	static String Quantity;
	static String currentString;
	static String searchString;
	private static String url = "http://rest.playboyviet.com/public/phototamtayvn-rest";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Get the view from listview_main.xml
		setContentView(R.layout.listview_main);
		inputSearch = (EditText) findViewById(R.id.inputSearch);
//		 getActionBar().setDisplayHomeAsUpEnabled(true);
		new DownloadJSON().execute();
		inputSearch.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				ArrayList<HashMap<String, String>> arrayTemplist = new ArrayList<HashMap<String, String>>();
				String searchString = inputSearch.getText().toString();
				for (int i = 0; i < arraylist.size(); i++) {
					currentString = arraylist.get(i).get(MainActivity.CONTENT);
					s = arraylist.get(i).get(MainActivity.CONTENT);
					if (currentString.trim().toLowerCase()
							.startsWith(searchString.trim().toLowerCase())) {
						arrayTemplist.add(arraylist.get(i));
					}
				}
				adapter = new ListViewAdapter(MainActivity.this, arrayTemplist);
				listview.setAdapter(adapter);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@SuppressLint("NewApi")
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.activity_main, menu);

		SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
				.getActionView();

		searchView.setSearchableInfo(searchManager
				.getSearchableInfo(getComponentName()));
		searchView.setIconifiedByDefault(false);

		SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener() {
			@Override
			public boolean onQueryTextChange(String newText) {
				// this is your adapter that will be filtered
//				adapter.getFilter().filter(newText);
				System.out.println("on text chnge text: " + newText);
				return true;
			}

			@SuppressLint("NewApi")
			@Override
			public boolean onQueryTextSubmit(String query) {
				// this is your adapter that will be filtered
//				adapter.getFilter().filter(query);
				System.out.println("on query submit: " + query);
				return true;
			}
		};
		searchView.setOnQueryTextListener(textChangeListener);

		return super.onCreateOptionsMenu(menu);

	}
	
	// DownloadJSON AsyncTask
	private class DownloadJSON extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(MainActivity.this);
			// Set progressdialog title
			mProgressDialog.setTitle("Phototamtay.vn");
			// Set progressdialog message
			mProgressDialog.setMessage("loading...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// Create an array
			arraylist = new ArrayList<HashMap<String, String>>();
			// Retrieve JSON Objects from the given URL address
			ServiceHandler sh = new ServiceHandler();

			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

			try {
				// Locate the array name in JSON
				JSONObject jsonObj = new JSONObject(jsonStr);
				jsonarray = jsonObj.getJSONArray("data");

				for (int i = 0; i < jsonarray.length(); i++) {
					HashMap<String, String> map = new HashMap<String, String>();
					jsonobject = jsonarray.getJSONObject(i);


					map.put("id", jsonobject.getString("id"));
					map.put("content_detail",
							jsonobject.getString("content_detail"));
					map.put("image_thumbnail",
							jsonobject.getString("image_thumbnail"));

					arraylist.add(map);
				}
				// Log.e("Array", "" + arraylist);
			} catch (JSONException e) {
				Log.e("Error", e.getMessage());
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			// Locate the listview in listview_main.xml
			listview = (ListView) findViewById(R.id.listview);
			// Pass the results into ListViewAdapter.java
			adapter = new ListViewAdapter(MainActivity.this, arraylist);
			// Set the adapter to the ListView
			listview.setAdapter(adapter);

			// Close the progressdialog
			mProgressDialog.dismiss();
		}
	}
}